const fs = require('fs');
const path = require('path');
const { promisify } = require('util');

// 将回调函数转换为Promise
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);

// 数据文件路径
const dataDir = path.join(__dirname, '../data');
const dataFiles = {
    airQuality: path.join(dataDir, 'air-quality.json'),
    pollutionRanking: path.join(dataDir, 'pollution-ranking.json'),
    temperatureHumidity: path.join(dataDir, 'temperature-humidity.json'),
    waterQuality: path.join(dataDir, 'water-quality.json'),
    energyConsumption: path.join(dataDir, 'energy-consumption.json'),
    monitoringStations: path.join(dataDir, 'monitoring-stations.json'),
    overviewStats: path.join(dataDir, 'overview-stats.json')
};

// 确保数据目录存在
const ensureDataDir = () => {
    if (!fs.existsSync(dataDir)) {
        fs.mkdirSync(dataDir, { recursive: true });
    }
};

// 读取数据文件
const readDataFile = async (fileKey) => {
    try {
        const filePath = dataFiles[fileKey];
        if (!filePath) {
            throw new Error(`未知的文件键: ${fileKey}`);
        }
        const data = await readFile(filePath, 'utf8');
        return JSON.parse(data);
    } catch (error) {
        console.error(`读取数据文件失败 ${fileKey}:`, error);
        throw error;
    }
};

// 写入数据文件
const writeDataFile = async (fileKey, data) => {
    try {
        const filePath = dataFiles[fileKey];
        if (!filePath) {
            throw new Error(`未知的文件键: ${fileKey}`);
        }
        await writeFile(filePath, JSON.stringify(data, null, 2));
        return data;
    } catch (error) {
        console.error(`写入数据文件失败 ${fileKey}:`, error);
        throw error;
    }
};

// 检查文件是否存在
const fileExists = (fileKey) => {
    const filePath = dataFiles[fileKey];
    return filePath ? fs.existsSync(filePath) : false;
};

// 读取所有数据文件
const readAllDataFiles = async () => {
    try {
        const results = {};
        for (const [key] of Object.entries(dataFiles)) {
            results[key] = await readDataFile(key);
        }
        return results;
    } catch (error) {
        console.error('读取所有数据文件失败:', error);
        throw error;
    }
};

module.exports = {
    dataFiles,
    ensureDataDir,
    readDataFile,
    writeDataFile,
    fileExists,
    readAllDataFiles
};